using System.Collections;
using System.Collections.Generic;
using GameFrameWork;
using UnityEngine;

/// <summary>
/// 雪花豌豆子弹 - 对目标造成伤害并施加减速效果
/// </summary>
public class SnowPeaBullet : Bullet
{
    private float m_SlowPercentage = 0.5f;
    private float m_SlowDuration = 3f;
    private bool m_HasSlowParameters = false;
    private int m_Pierce; // 穿透计数

    /// <summary>
    /// 设置减速参数（由攻击策略调用）
    /// </summary>
    public void SetSlowParameters(float slowPercentage, float slowDuration)
    {
        m_SlowPercentage = slowPercentage;
        m_SlowDuration = slowDuration;
        m_HasSlowParameters = true;
    }

    protected override void OnTriggerEnter2D(Collider2D other)
    {
        Logger.Log($"[SnowPeaBullet OnTriggerEnter2D] 子弹命中 ===>>> {other.gameObject.name}");
        var entity = other.GetComponent<Entity>();
        if (entity != null)
        {
            // 如果是第一次命中，初始化穿透计数
            if (m_Pierce == 0)
            {
                InitializePierce();
            }

            // 先执行伤害效果（排除减速Buff效果）
            ExecuteDamageEffects(entity);

            // 如果设置了减速参数，应用减速效果（包括Buff和颜色变化）
            if (m_HasSlowParameters && entity.BuffComponent != null)
            {
                ApplySlowEffect(entity);
            }

            // 处理穿透
            HandlePierce();
        }
        else
        {
            Logger.Log("SnowPeaBullet", $"命中的对象不是Entity: {other.gameObject.name}");
        }
    }

    /// <summary>
    /// 执行伤害效果（排除减速Buff效果）
    /// </summary>
    private void ExecuteDamageEffects(Entity target)
    {
        if (m_Entity == null || target == null)
        {
            return;
        }

        // 获取子弹数据
        var bulletData = m_Entity.EntityData?.AttackData?.BulletData;
        if (bulletData == null || bulletData.Effects == null)
        {
            Logger.LogWarning("SnowPeaBullet", $"子弹数据或效果列表为空");
            return;
        }

        // 执行所有效果，但排除 AddBuffEffectData（减速Buff由 ApplySlowEffect 处理）
        foreach (var effect in bulletData.Effects)
        {
            if (effect is AddBuffEffectData addBuffEffect)
            {
                // 跳过减速Buff效果，由 ApplySlowEffect 处理
                if (addBuffEffect.BuffData is SlowData)
                {
                    Logger.Log("SnowPeaBullet", $"跳过减速Buff效果，将由 ApplySlowEffect 处理");
                    continue;
                }
            }
            
            // 执行其他效果（如伤害）
            effect.Execute(m_Entity, target);
        }
    }

    /// <summary>
    /// 应用减速效果（包括Buff和颜色变化）
    /// </summary>
    private void ApplySlowEffect(Entity target)
    {
        if (target == null || target.BuffComponent == null)
        {
            return;
        }

        // 从 BulletData.Effects 中查找 AddBuffEffectData，获取 SlowData
        SlowData slowData = null;
        float colorDuration = m_SlowDuration;

        // 获取子弹数据
        var bulletData = m_Entity?.EntityData?.AttackData?.BulletData;
        if (bulletData != null && bulletData.Effects != null)
        {
            foreach (var effect in bulletData.Effects)
            {
                if (effect is AddBuffEffectData addBuffEffect)
                {
                    if (addBuffEffect.BuffData is SlowData foundSlowData)
                    {
                        slowData = foundSlowData;
                        colorDuration = foundSlowData.Duration;
                        Logger.Log("SnowPeaBullet", $"从 BulletData.Effects 中找到 SlowData: {foundSlowData.BuffName}, Duration={foundSlowData.Duration}, SlowPercentage={foundSlowData.SlowPercentage * 100}%");
                        break;
                    }
                }
            }
        }

        // 如果没有找到，使用保存的参数创建 SlowData
        if (slowData == null)
        {
            Logger.LogWarning("SnowPeaBullet", $"未在 BulletData.Effects 中找到 SlowData，使用保存的参数创建");
            slowData = ScriptableObject.CreateInstance<SlowData>();
            slowData.BuffName = "雪花减速";
            slowData.BuffType = BuffType.Slow;
            slowData.Duration = m_SlowDuration;
            slowData.SlowPercentage = m_SlowPercentage;
            slowData.IsCanMerge = true;
            slowData.Tags = BuffTag.Slow;
        }

        // 立即变蓝
        target.SetColor(Color.blue, colorDuration);

        // 添加减速Buff
        target.BuffComponent.AddBuff(slowData, m_Entity, target);
        
        Logger.Log("SnowPeaBullet", $"{target.name} 被雪花子弹减速 {slowData.SlowPercentage * 100}%，持续 {colorDuration} 秒");
    }

    /// <summary>
    /// 处理穿透逻辑
    /// </summary>
    private void HandlePierce()
    {
        // 减少穿透计数
        m_Pierce--;
        Logger.Log("SnowPeaBullet", $"穿透后剩余: {m_Pierce}");
        
        // 如果穿透次数用完，回收子弹
        if (m_Pierce <= 0)
        {
            Logger.Log("SnowPeaBullet", $"穿透次数用完，回收子弹");
            BulletPool.Instance.ReturnBullet(this);
        }
    }

    /// <summary>
    /// 初始化穿透计数（在 Initialize 之后调用，或通过反射获取基类的 m_Pierce）
    /// </summary>
    private void InitializePierce()
    {
        // 从 BulletData 获取穿透次数
        var bulletData = m_Entity?.EntityData?.AttackData?.BulletData;
        if (bulletData != null)
        {
            m_Pierce = bulletData.MaxPierce;
            Logger.Log("SnowPeaBullet", $"初始化穿透计数: {m_Pierce}");
        }
    }
}
